package com.yys.gulimall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.yys.gulimall.order.config.AlipayTemplate;
import com.yys.gulimall.order.service.OrderService;
import com.yys.gulimall.order.vo.PayAsyncVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author zq
 * @version 1.0
 * @date 2021/4/7 16:41
 */
@RestController
@Slf4j
public class OrderPayedListener {

    @Autowired
    private OrderService orderservice;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo,HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {

        // 这里首先验签 验证是支付宝发来的请求
        HashMap<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for(Iterator<String> iter = requestParams.keySet().iterator();iter.hasNext();){
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for(int i = 0;i<values.length;i++) {
                valueStr = (i==values.length -1)?valueStr + values[i] : valueStr + values[i] + ",";
            }
            valueStr = new String(valueStr.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
            params.put(name,valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type());
//        if(signVerified) {
            // 收到支付宝异步通知,返回success,支付宝不再通知
            log.info("收到支付宝通知: {}",payAsyncVo);
            return orderservice.handlePayResult(payAsyncVo);
//        }
//        log.info("签名认证失败...");
//        return "false";

    }
}
